import {h, defineComponent, watch} from 'vue'
import {Form, Select} from 'ant-design-vue';
import ajax from '@/utils/ajax'
import {empty, setObjectValue} from "@/utils/index"
import { useVModel } from '@vueuse/core'
import useRemoteOptions from '@/hook/remoteOptions.js'
import { useInjectFormContext } from '@/components/form/context'
export default defineComponent({
    name:'ExSelect',
    props:{
        changeLoadOptions:{
            type:Array,
            default:[],
        },
        remote:Object,
        options:Array,
    },
    emits:['update:options'],
    setup(props,ctx){
        const formItemContext = Form.useInjectFormItemContext();
        watch(()=>ctx.attrs.value,value=>{
            formItemContext.onFieldChange()
        })
        const formContext = useInjectFormContext()
        const options  = useVModel(props,'options',ctx.emit)
        const {remoteOptionsDebounce,remoteOptions} = useRemoteOptions(props,options)
        changeLoad()
        if(!empty(ctx.attrs.value)){
            if(Array.isArray(ctx.attrs.value)){
                remoteOptions('')
            }else {
                remoteOptions(ctx.attrs.value)
            }
        }
        function changeLoad() {
            props.changeLoadOptions.forEach(item=>{
                changeLoadOptions(item.params,item.updateObject, ctx.attrs.value)
            })
        }
        function changeLoadOptions(params,updateObject,value) {
            params.data.value = value
            if(formContext){
                params.data.data = formContext.submitData()
            }
            ajax(params).then(res => {
                if(res.data){
                    for (let field in res.data) {
                        setObjectValue(updateObject, field, res.data[field])
                    }
                }
            })
        }
        return {
            remoteOptionsDebounce,
            remoteOptions,
            options
        }
    },
    render(e){
        let props = Object.assign({
           onDropdownVisibleChange:(open)=>{
               if(open){
                   this.remoteOptions('')
               }
           }
        },e.$attrs)
        if(props.showSearch){
            props.onSearch = value=>{
                this.remoteOptionsDebounce(value)
            }
        }
        if(!e.$attrs.options && e.options){
            props.options = e.options
        }
        return h(Select, props, e.$slots)
    }
})
